package com.AdvancedDemos.Learn网络编程.CS架构.useTCP1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class Client {
    public static void main(String[] args) throws IOException {
        //Client发送数据,Server接收数据
        //客户端socket
        System.out.println("客户端开启");
        Socket socket = new Socket(/*"127.0.0.1"*/InetAddress.getLocalHost(), 8888);
        System.out.println("连接成功");
        //发送数据
        System.out.println("发送数据");
        String data = "你好吗?";
        //获取输出字节流
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(data.getBytes());
//        outputStream.close(); socket.getOutputStream()拿到的outputStream的close被重写了,会直接关闭socket

        //告知服务器发送完毕
        socket.shutdownOutput();
        System.out.println("不再发送");

        //接收数据
        System.out.println("接收数据");
        InputStream inputStream = socket.getInputStream();
        int len;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)/*阻塞,等待发送数据*/) != -1) {//跳出循环不是因为len=-1,而是因为server关闭了socket连接
            String s = new String(bytes, 0, len);
            System.out.println(s);
        }
//        inputStream.close();socket.getInputStream()拿到的inputStream的close被重写了,会直接关闭socket

        System.out.println("关闭资源");
        socket.close();
    }
}
